package com.ygxsk.carhome.ui.zxing;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.FlashlightUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.EventBusQRCode;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.qrcode.core.BarcodeType;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/*
 * @Author:itchenqi
 * @Time:2020/7/27 0027  14:44
 * @Description: 我的zbar二维码扫描器的集成类
 */
public class MyBGAQRCodeActivity extends ErrorActivity implements ErrorParentExtraSingle, QRCodeView.Delegate, EasyPermissions.PermissionCallbacks {

    private static final int REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666;

    //选择图片的标识内容;
    private static final int PRC_PHOTO_PICKER = 1;

    //扫描二维码需要的部分权限
    private static final int REQUEST_CODE_QRCODE_PERMISSIONS = 2;

    /**
     * 扫描二维码的布局内容
     */
    @BindView(R.id.zbarviewinmy)
    ZBarView mZBarView;

    //--------------------------------------------------
    /**
     * 打开闪光灯的布局
     */
    @BindView(R.id.flashLightLayoutinmyopen)
    LinearLayoutCompat flashLightLayoutOpen;

    /**打开闪光灯的图片内容信息*/
    //@BindView(R.id.flashLightIvinmyopen)
    //AppCompatImageView flashLightIvOPEN;

    /**打开闪光灯的文字内容*/
    //@BindView(R.id.flashLightTvinmyopen)
    //TextView flashLightTv;

    /**
     * 关闭闪光灯的布局
     */
    @BindView(R.id.flashLightLayoutinmyclose)
    LinearLayoutCompat flashLightLayoutClose;

    //--------------------------------------------------
    /**
     * 打开相册的布局
     */
    @BindView(R.id.albumLayoutinmy)
    LinearLayoutCompat albumLayout;

    //--------------------------------------------

    private BeepManager beepManager;

//    private PermissionSetting mSetting;


    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    /**
     * 跳转到扫描二维码的标识内容，，是从哪个界面跳转过来的扫描
     */
    private int bgaqrcode_key_form_where;
    //携带是哪种类型的扫描--二维码或者一维码，或者二者都有,暂时没用到，但是勿删，后边可能用到；
    private int extra_qrcode_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        // 保持Activity处于唤醒状态
//        Window window = getWindow();
//        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            window.setStatusBarColor(Color.BLACK);
//        }

//        mSetting = new PermissionSetting(this);

        mZBarView.setDelegate(this);

        //mZBarView.showScanRect();//显示扫描框。 和底下的代码重复了。
        //mZBarView.startSpotAndShowRect();//显示扫描框并开始识别。
        //mZBarView.getScanBoxView().setOnlyDecodeScanBoxArea(false); // 识别整个屏幕中的码

        //默认设置为false
        //FlashlightUtils.setFlashlightStatus(false);

        initViews();

        beepManager = new BeepManager(this);
        if (beepManager != null) {
            beepManager.setPlayBeep(true);
            //beepManager.setVibrate(true);
        }

        //需要相机的权限
        /*AndPermission.with(MyBGAQRCodeActivity.this)
                .runtime()//
                .permission(Permission.READ_PHONE_STATE,//
                        Permission.CAMERA,//
                        Permission.READ_EXTERNAL_STORAGE,//
                        Permission.WRITE_EXTERNAL_STORAGE)//
                .rationale(new RuntimeRationale())
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        //这里代码是为了让用户下载 访问存放APK路径
                    }
                }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> permissions) {

                if (AndPermission.hasAlwaysDeniedPermission(MyBGAQRCodeActivity.this, permissions)) {
                    mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, MyBGAQRCodeActivity.this, permissions);
                }

            }
        }).start();*/

    }

    @Override
    protected void onStart() {
        //打开后置摄像头开始预览，但是并未开始识别
        super.onStart();
        //申请权限内容

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU");

            requestCodeQRCodePermissions();

        } else {

            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "Build.VERSION.SDK_INT 大于 Build.VERSION_CODES.TIRAMISU  android13");

            requestCodeQRCodePermissionsXXPermissions();

        }


    }

    @AfterPermissionGranted(REQUEST_CODE_QRCODE_PERMISSIONS)
    private void requestCodeQRCodePermissions() {

        try {

            //do

            //小于Android13
            String[] perms = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

            if (EasyPermissions.hasPermissions(this, perms)) {

                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "已经有权限了-EasyPermissions.hasPermissions");

                openMain();

            } else {

                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "还没有权限  -EasyPermissions.hasPermissions");
                CommUtils.checkMaterialDialog(materialDialog);

                materialDialog = CommUtils.authorityRequest(MyBGAQRCodeActivity.this, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_CAMERA_STORAGE, new AuthorityCallbackListener() {
                    @Override
                    public void doSomeThing() {

                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "已经弹出了 权限内容弹窗");

                        CommUtils.checkMaterialDialog(materialDialog);

                        //如果没有这两个权限，
                        EasyPermissions.requestPermissions(MyBGAQRCodeActivity.this,//
                                StringUtils.getString(R.string.qrcoderequestpermissions),//
                                REQUEST_CODE_QRCODE_PERMISSIONS,//
                                perms);//

                    }
                });

            }

        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }

    }


    private void openMain() {

        //如果有这个权限，就该执行什么逻辑，就执行什么逻辑。
        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "已经获取到权限 就该执行什么逻辑");

        //如果有这两个权限，直接 正常执行代码
        if (mZBarView != null) {

            mZBarView.getScanBoxView().setOnlyDecodeScanBoxArea(false); // 仅识别扫描框中的码
            mZBarView.setType(BarcodeType.ALL, null); // 识别所有类型的码

            mZBarView.startCamera();//打开后置摄像头预览,但并没有开始扫描
            mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
            //暂时设置为 仅仅识别扫描框之中的二维码，如果将来效果不好再识别整个屏幕；
            //识别整个屏幕，会延迟扫描或者扫描不精准
            //mZBarView.getScanBoxView().setOnlyDecodeScanBoxArea(false); // 识别整个屏幕中的码

        }

    }

    //使用XXPermissions改造
    private void requestCodeQRCodePermissionsXXPermissions() {

        //|| !XXPermissions.isGranted(MyBGAQRCodeActivity.this, com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
        //|| !XXPermissions.isGranted(MyBGAQRCodeActivity.this, com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//

        if (!XXPermissions.isGranted(MyBGAQRCodeActivity.this, com.hjq.permissions.Permission.CAMERA)//
                || !XXPermissions.isGranted(MyBGAQRCodeActivity.this, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(MyBGAQRCodeActivity.this, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "已经弹出了 权限内容弹窗");
                    XXPermissions.with(MyBGAQRCodeActivity.this)
                            // 适配分区存储应该这样写
                            //.permission(Permission.Group.STORAGE)
                            // 不适配分区存储应该这样写
                            .permission(com.hjq.permissions.Permission.CAMERA)//
                            .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//
                            //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
//                                                        .interceptor(new PermissionInterceptor())
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                    if (!allGranted) {
                                        // TODO: 2024/1/23 18:50 权限这里要不要给提示？权限没通过

                                        return;
                                    }

                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                            PermissionNameConvert.getPermissionString(MyBGAQRCodeActivity.this, permissions)));

                                    openMain();

                                }
                            });
                }
            });

        } else {

            openMain();

        }

    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_my_b_g_a_q_r_code;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle("二维码扫描");

        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

//        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                methodBack();
//            }
//        });

//        toolbarHelper.setLayoutClose(false, "", null);

//        toolbarHelper.setLayoutRight(false, 0, "", null);

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected void onClickNodata(View v) {

        //暂时没用到

    }

    @Override
    protected void initViews() {

        //三个内容
        //第一 判断有闪光灯就展示，没有就不展示
        /*有闪光灯就显示手电筒按钮  否则不显示*/
        if (FlashlightUtils.isFlashlightEnable()) {//该设备是否有闪光灯

            Delivery.getInstance().post(new Runnable() {
                @Override
                public void run() {

                    if (flashLightLayoutOpen != null) {

                        flashLightLayoutOpen.setVisibility(View.VISIBLE);

                        //执行打开 闪光灯功能
                        flashLightLayoutOpen.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                if (!DoubleClickListener.isFastDoubleClick()) {

                                    if (mZBarView != null) {
                                        mZBarView.openFlashlight();
                                    }
                                }

                            }
                        });
                    }

                    if (flashLightLayoutClose != null) {

                        flashLightLayoutClose.setVisibility(View.VISIBLE);

                        //执行关闭 闪光灯功能
                        flashLightLayoutClose.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                if (!DoubleClickListener.isFastDoubleClick()) {

                                    if (mZBarView != null) {
                                        mZBarView.closeFlashlight();
                                    }

                                }
                            }
                        });
                    }

                }
            });

        } else {

            Delivery.getInstance().post(new Runnable() {
                @Override
                public void run() {

                    if (flashLightLayoutOpen != null) {
                        flashLightLayoutOpen.setVisibility(View.GONE);
                    }

                    if (flashLightLayoutClose != null) {
                        flashLightLayoutClose.setVisibility(View.GONE);
                    }
                }
            });

        }

        //从相册选择的功能
        if (albumLayout != null) {
            albumLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                        choicePhotoWrapper();

                    } else {

                        choicePhotoWrapperXXPermissions();

                    }

                }
            });
        }

    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {

        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

        if (EasyPermissions.hasPermissions(this, perms)) {

            photoPicker();

        } else {

//            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片\n\n2.拍照", PRC_PHOTO_PICKER, perms);
            EasyPermissions.requestPermissions(this, getResources().getString(R.string.imageselectstr), PRC_PHOTO_PICKER, perms);

        }

    }


    private void photoPicker() {

                 /*
                 这里也是需要验证权限的：
                从相册选取二维码图片，这里为了方便演示，使用的是
                https://github.com/bingoogolapple/BGAPhotoPicker-Android
                这个库来从图库中选择二维码图片，这个库不是必须的，你也可以通过自己的方式从图库中选择图片
                 */
        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(MyBGAQRCodeActivity.this)
                .cameraFileDir(null)
                .maxChooseCount(1)
                .selectedPhotos(null)
                .pauseOnScroll(false)
                .build();

        startActivityForResult(photoPickerIntent, REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY);

    }

    //从相册选择图片
    private void choicePhotoWrapperXXPermissions() {

        if (!XXPermissions.isGranted(MyBGAQRCodeActivity.this,
                com.hjq.permissions.Permission.READ_MEDIA_IMAGES
//            com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
        )) {//com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {

                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    XXPermissions.with(MyBGAQRCodeActivity.this)
                            // 适配分区存储应该这样写
                            //.permission(Permission.Group.STORAGE)
                            // 不适配分区存储应该这样写
//                          .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
                            .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
                            .interceptor(new PermissionInterceptor())
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                    if (!allGranted) {
                                        return;
                                    }

                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                            PermissionNameConvert.getPermissionString(MyBGAQRCodeActivity.this, permissions)));

                                    photoPicker();

                                }
                            });

                }
            });

        } else {

            photoPicker();

        }

    }


    @Override
    protected void gainDatas() {

        //暂时不要

    }

    @Override
    protected void methodBack() {

        if (ActivityUtils.isActivityAlive(MyBGAQRCodeActivity.this)) {
            ActivityUtils.finishActivity(MyBGAQRCodeActivity.this);
        }

    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {

        //扫描成功之后的返回
        LogUtils.d("itchen----扫描成功之后的回调----onScanQRCodeSuccess--->" + result);

        //32c48fe0534459bc63d3098c53142ed3

        //扫描成功之后震动。
        //VibrateUtils.vibrate(200);

        if (beepManager != null) {
            beepManager.playBeepSoundAndVibrate();
        }

        vibrate();

        //这个会导致重复识别, 后边看看怎么处理？
        //2020-10-13 15:53:28 如果不是 【设备保养过来的】那么要 频繁再次扫码
        // : 2023-06-10 扫码待处理
//        if (bgaqrcode_key_form_where == ExtraValue.BGAQRCODE_VALUE_FROM_WEBVIEW) {//|| bgaqrcode_key_form_where == ExtraValue.BGAQRCODE_VALUE_FROM_ORDER_LIST
        //如果是订单列表的核销，就不能使用再次扫描，会打开多个页面；
        if (mZBarView != null) {
            //2020-7-28 08:42:21 有可能这次扫码失败，如果扫码失败 继续保持唤醒以便于继续识别。
            mZBarView.startSpot(); // 开始识别  有的网页上说： 再次延时1.5秒后启动
        }
//        }

        //itchen 自己添加代码：目的为了让扫码声音延缓一段时间。
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //发送消息 给巡检详情界面或者保养详情界面，
        if (!TextUtils.isEmpty(result)) {

            // : 2023-06-10 结果的回显待处理,后续可能有其他的扫描需求，故做个区分；
            if (bgaqrcode_key_form_where == ExtraValue.BGAQRCODE_VALUE_FROM_CARD_DIST_HISTORY) {

//                LogUtils.d("itchen----->EventBus发送通知-【客户关怀-卡券核销】- 详情扫码成功");
                LogUtils.d("itchen----->EventBus发送通知-【餐券发放-餐券核销】-  详情扫码成功");

                EventBusQRCode eventBusQRCode = new EventBusQRCode();
                eventBusQRCode.setMessage(ExtraValue.BGAQRCODE_VALUE_FROM_CARD_DIST_HISTORY);
                //result是一段json 携带卡券的有效期；
                eventBusQRCode.setContent(result);
                EventBus.getDefault().post(eventBusQRCode);

            } else if (bgaqrcode_key_form_where == ExtraValue.BGAQRCODE_VALUE_FROM_ORDER_LIST) {

                //BGAQRCODE_VALUE_FROM_ORDER_LIST

//                LogUtils.d("itchen----->EventBus发送通知-【商品订单-卡券核销】-  详情扫码成功---BGAQRCODE_VALUE_FROM_ORDER_LIST");

                // : 2023-08-20 17:11 数据截断，尽量让只发送一条数据；
                EventBusQRCode eventBusQRCode = new EventBusQRCode();
                eventBusQRCode.setMessage(ExtraValue.BGAQRCODE_VALUE_FROM_ORDER_LIST);
                //result是一段json 携带卡券的有效期；
                eventBusQRCode.setContent(result);
                EventBus.getDefault().post(eventBusQRCode);

//                mCompositeDisposable.add(Observable.create(new ObservableOnSubscribe<String>() {
//                            @Override
//                            public void subscribe(@io.reactivex.rxjava3.annotations.NonNull ObservableEmitter<String> emitter) throws Throwable {
//
//                                emitter.onNext("1");
//                                emitter.onComplete();
//
//                            }
//                        }).throttleFirst(3, TimeUnit.SECONDS)
//                        .subscribe(new Consumer<String>() {
//                            @Override
//                            public void accept(String valueStr) throws Throwable {
//
//                                // : 2023-08-20 17:11 数据截断，尽量让只发送一条数据；
//                                EventBusQRCode eventBusQRCode = new EventBusQRCode();
//                                eventBusQRCode.setMessage(ExtraValue.BGAQRCODE_VALUE_FROM_ORDER_LIST);
//                                //result是一段json 携带卡券的有效期；
//                                eventBusQRCode.setContent(result);
//                                EventBus.getDefault().post(eventBusQRCode);
//
//                            }
//                        }));

            } else if (bgaqrcode_key_form_where == ExtraValue.BGAQRCODE_VALUE_FROM_PAINT_BOOK_SUMHISTORY) {

                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "消息是从 喷涂预约的 扫描二维码过来的");

                EventBusQRCode eventBusQRCode = new EventBusQRCode();
                eventBusQRCode.setMessage(ExtraValue.BGAQRCODE_VALUE_FROM_PAINT_BOOK_SUMHISTORY);
                //result是一段json 携带卡券的有效期；
                eventBusQRCode.setContent(result);
                EventBus.getDefault().post(eventBusQRCode);

            } else if (bgaqrcode_key_form_where == ExtraValue.BGAQRCODE_VALUE_FROM_HOME_MAIN) {

                //消息是从 首页的扫一扫过来的，2023-12-14 14:23:00开发这个逻辑是因为 喷涂中心扫一扫。

                EventBusQRCode eventBusQRCode = new EventBusQRCode();
                eventBusQRCode.setMessage(ExtraValue.BGAQRCODE_VALUE_FROM_HOME_MAIN);
                //result是一段json 携带卡券的有效期；
                eventBusQRCode.setContent(result);
                EventBus.getDefault().post(eventBusQRCode);

            }

            //扫码成功之后 立即杀死该界面
            if (ActivityUtils.isActivityAlive(MyBGAQRCodeActivity.this)) {
                ActivityUtils.finishActivity(MyBGAQRCodeActivity.this);
            }

        } else {

            //提示扫码失败：还继续停留在扫码的布局上
            ToastUtils.showShort(R.string.qrcodefailstring);

            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "扫码失败的结果--result-->" + result);

        }

    }

    @Override
    protected void onResume() {
        super.onResume();

        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "onResume--onResume--onResume");

        if (beepManager != null) {
            beepManager.updatePrefs();
        }

    }

    @Override
    protected void onPause() {

        if (beepManager != null) {
            beepManager.close();
        }

        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mZBarView != null) {
            mZBarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (mZBarView != null) {
            // 销毁二维码扫描控件
            mZBarView.onDestroy();
        }
        super.onDestroy();
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        if (mZBarView != null) {

            String tipText = mZBarView.getScanBoxView().getTipText();
            String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
            if (isDark) {
                if (!tipText.contains(ambientBrightnessTip)) {
                    mZBarView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
                }
            } else {
                if (tipText.contains(ambientBrightnessTip)) {
                    tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                    mZBarView.getScanBoxView().setTipText(tipText);
                }
            }

        }

    }

    @Override
    public void onScanQRCodeOpenCameraError() {

        //LogUtils.d("itchen------->打开相机时候出错。");

        ToastUtils.showShort("打开相机时候出错~");

    }

    @Override
    public void processExtraData() {

        //填充跳转布局
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            //添加标识
            bgaqrcode_key_form_where = bundle.getInt(ExtraKey.BGAQRCODE_KEY);

            //携带 是那种类型的 扫描携带标识
            extra_qrcode_info = bundle.getInt(ExtraKey.EXTRA_QRCODE_INFO);

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        //同意 权限的操作
        // TODO: 2023-06-12 16:03 这里是执行扫描的操作

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        //未能同意权限的操作
        if (requestCode == PRC_PHOTO_PICKER) {
            //Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
            ToastUtils.showShort("您拒绝了「图片选择」所需要的相关权限!");

        } else if (requestCode == REQUEST_CODE_QRCODE_PERMISSIONS) {

            //拒绝了扫描二维码的权限
            ToastUtils.showShort("您拒绝了「扫描二维码」所需要的相关权限!");

        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //--------------------------------------------------------------
        if (mZBarView != null) {
            //显示扫描框：为了避免再次回来的时候扫描框失效。
//            mZBarView.showScanRect();
            mZBarView.startSpotAndShowRect();

        } else {
            LogUtils.d("itchen--执行到mZBarView的值-->是空的");
        }
        //--------------------------------------------------------------

        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY) {

            //因为仅仅只有一张图片
            final String picturePath = BGAPhotoPickerActivity.getSelectedPhotos(data).get(0);
            LogUtils.d("itchen--执行到onActivityResult的picturePath是空值-->" + picturePath);

            //一个耗时的操作，最好放在子线程执行。所以这个 decodeQRCode 方法是一个内部类。
            if (mZBarView != null) {

                if (!TextUtils.isEmpty(picturePath)) {

                    //转bitmap?
                    Bitmap bitmap = ImageUtils.getBitmap(picturePath);

                    if (bitmap != null) {
                        mZBarView.decodeQRCode(bitmap);
                    } else {
                        //如果转换不出来那么识别正常的路径
                        mZBarView.decodeQRCode(picturePath);
                    }

                } else {

                    LogUtils.d("itchen--执行到onActivityResult的picturePath是空值");
                    ToastUtils.showShort("执行到onActivityResult的picturePath是空值~");

                }
            }


        }

    }


}